package com.dmz.workflow.interceptor;

import com.dmz.workflow.util.ObjectUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

@Aspect
@Component
@EnableAspectJAutoProxy
public class ServiceLogAspect {
    private Logger logger = LoggerFactory.getLogger(ServiceLogAspect.class);

    ThreadLocal<Long> timeDuration = new ThreadLocal<>();

    @Pointcut("execution(* com.echronos.workflow.service.*.*(..))")
    private void serviceAspect() {
    }

    @Before(value = "serviceAspect()")
    public void methodBefore(JoinPoint joinPoint) {
        timeDuration.set(System.currentTimeMillis());
        if (ObjectUtils.isNotEmpty(joinPoint)) {
            logger.info("Request service class:{} method:{} parameters:{}",
                    joinPoint.getTarget().getClass().getName(),
                    joinPoint.getSignature().getName(),
                    joinPoint.getArgs());
        }
    }

    @AfterReturning(returning = "result", pointcut = "serviceAspect()")
    public void methodAfterReturning(Object result) {
        logger.info("请求处理时间为:" + (System.currentTimeMillis() - timeDuration.get()));
    }
}
